#!/usr/bin/env python
#-*- coding:utf-8 -*-

from sqlalchemy import Column, Integer, String, Sequence, Text
from models.base import Base
from config.utils import get_database_session
import hashlib


def _md5(s):
    return hashlib.md5(s.encode('utf8')).hexdigest()


class User(Base):
    __tablename__ = "users"

    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    name = Column(String(50))
    fullname = Column(String(50))
    password = Column(String(60))

    def __repr__(self):
        return "<User(%s)>" % self.name

    def check_password(self, pswd):
        return self.password == _md5(pswd)


class Session(Base):
    __tablename__ = "sessions"

    id = Column(String(40), primary_key=True)
    content = Column(Text())


def auth_user(username, password):
    db_session = get_database_session()
    user = db_session.query(User).filter_by(name=username).first()
    if not user:
        return None
    if user.check_password(password):
        return user
    return None
